import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { isLoggedIn } from '@/services/userService'

const Home = () => import('@/views/Home.vue')
const Posts = () => import('@/views/Posts.vue')
const PostEdit = () => import('@/views/PostEdit.vue')
const ArticleEdit = () => import('@/views/ArticleEdit.vue')
const Categories = () => import('@/views/Categories.vue')
const Category = () => import('@/views/Category.vue')
const About = () => import('@/views/About.vue')
const ArticleDetail = () => import('@/views/ArticleDetail.vue')
const Login = () => import('@/views/Login.vue')
const Register = () => import('@/views/Register.vue')

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'home', component: Home },
    { path: '/posts', name: 'posts', component: Posts },
    // 统一使用基于 id 的详情页
    { path: '/article/:id', name: 'article-detail', component: ArticleDetail, props: true },
    { path: '/post/:slug/edit', name: 'post-edit', component: PostEdit, props: true, meta: { requiresEditAuth: true } },
    { path: '/categories', name: 'categories', component: Categories },
    { path: '/category', name: 'category', component: Category },
    { path: '/about', name: 'about', component: About },
    { path: '/article/new', name: 'article-new', component: ArticleEdit, meta: { requiresAuth: true } },
    { path: '/article/:id/edit', name: 'article-edit', component: ArticleEdit, props: true, meta: { requiresAuth: true } },
    { path: '/login', name: 'login', component: Login },
    { path: '/register', name: 'register', component: Register },
    { path: '/:pathMatch(.*)*', redirect: '/' },
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition
    if (to.hash) return { el: to.hash, behavior: 'smooth' }
    return { top: 0 }
  },
})

router.beforeEach((to, from, next) => {
  // 检查是否需要登录
  if (to.meta?.requiresAuth) {
    if (!isLoggedIn()) {
      ElMessage.warning('请先登录')
      return next({ path: '/login' })
    }
  }
  
  // 保留旧的编辑权限检查（兼容性）
  if (to.meta?.requiresEditAuth) {
    const canEdit = localStorage.getItem('canEdit') === '1'
    if (!canEdit) {
      ElMessage.warning('当前无编辑权限（本地模拟）')
      return next({ path: '/' })
    }
  }
  next()
})

export default router


